﻿using Coomtools.commclass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Coomtools.weightclasses
{

public class Aclas32 : Myweightbase, IweightInteface

  

    {       
        // ****************32模式厂家预定义常数 大多用不到**********************************************
        #region 厂家预定义常数

        // Success
        const int ASSDK_Err_Success = 0x0000;
        // Progress
        const int ASSDK_Err_Progress = 0x0001;
        // Terminate by hand
        const int ASSDK_Err_Terminate = 0x0002;

        // ProtocolType
        const int ASSDK_ProtocolType_None = 0;
        const int ASSDK_ProtocolType_Pecr = 1;
        const int ASSDK_ProtocolType_Hecr = 2;
        const int ASSDK_ProtocolType_TSecr = 3;

        // ProcType
        const int ASSDK_ProcType_Down = 0;
        const int ASSDK_ProcType_UP = 1;
        const int ASSDK_ProcType_Edit = 2;
        const int ASSDK_ProcType_Del = 3;
        const int ASSDK_ProcType_List = 4;
        const int ASSDK_ProcType_Empty = 5;
        const int ASSDK_ProcType_Reserve = 0x0010;

        // DataType
        const int ASSDK_DataType_PLU = 0x0000;
        const int ASSDK_DataType_Unit = 0x0001;
        const int ASSDK_DataType_Department = 0x0002;
        const int ASSDK_DataType_HotKey = 0x0003;
        const int ASSDK_DataType_Group = 0x0004;
        const int ASSDK_DataType_Discount = 0x0005;
        const int ASSDK_DataType_Origin = 0x0006;
        const int ASSDK_DataType_Country = 0x0007;
        const int ASSDK_DataType_SlaughterHouse = 0x0008;
        const int ASSDK_DataType_Cuttinghall = 0x0009;
        const int ASSDK_DataType_Tare = 0x000A;
        const int ASSDK_DataType_Nutrition = 0x000B;
        const int ASSDK_DataType_Note1 = 0x000C;
        const int ASSDK_DataType_Note2 = 0x000D;
        const int ASSDK_DataType_Note3 = 0x000E;
        //const int ASSDK_DataType_TextMessage = 0x000F;
        const int ASSDK_DataType_Options = 0x0010;
        const int ASSDK_DataType_CustomBarcode = 0x0011;
        const int ASSDK_DataType_LabelPrintRecord = 0x0012;
        const int ASSDK_DataType_HeaderInfo = 0x0013;
        const int ASSDK_DataType_FooterInfo = 0x0014;
        const int ASSDK_DataType_AdvertisementInfo = 0x0015;
        const int ASSDK_DataType_HeaderLogo = 0x0016;
        const int ASSDK_DataType_FooterLogo = 0x0017;
        const int ASSDK_DataType_LabelAdvertisement = 0x0018;
        const int ASSDK_DataType_VendorInfo = 0x0019;
        const int ASSDK_DataType_NutritionElement = 0x001A;
        const int ASSDK_DataType_NutritionInfo = 0x001B;
        const int ASSDK_DataType_Note4 = 0x001C;


        #endregion

        //整数IP地址： 就是IP地址的无符号整数（UInt32）表达形式 例如 192.168.2.208 转换为整数为：192*256*256*256+168*256*256+2*256+208=3232236240
        //  *********************************导入dll声明***********************************************

        #region 导入dll声明
        const string LibraryName = "ExtrDlls/AclasSDK.dll";
        //const string LibraryName = "AclasSDK.dll";
        /// <summary>
        /// 32模式设备信息结构体
        /// </summary>
        [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1)]
        public struct TASSDKDeviceInfo
        {
            public UInt32 ProtocolType; // ProtocolType
            public UInt32 Addr;
            public UInt32 Port;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            public byte[] Name;
            public UInt32 ID;
            public UInt32 Version;
            public Byte Country;
            public Byte DepartmentID;
            public Byte KeyType;
            public UInt64 PrinterDot;
            public long PrnStartDate;
            public UInt32 LabelPage;
            public UInt32 PrinterNo;
            public UInt16 PLUStorage;
            public UInt16 HotKeyCount;
            public UInt16 NutritionStorage;
            public UInt16 DiscountStorage;
            public UInt16 Note1Storage;
            public UInt16 Note2Storage;
            public UInt16 Note3Storage;
            public UInt16 Note4Storage;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
            public byte[] FirmwareVersion;//固件版本
            public Byte DefaultProtocol;//默认协议            
            public Byte LFCodeLen;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public byte[] DeviceId; //档口号
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public byte[] StockId;//门店号
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 155)]
            public byte[] Adjunct;// 保留参数
        }
        /// <summary>
        /// 异步执行时的进度信息回调函数
        /// </summary>
        /// <param name="nErrorCode">错误代码</param>
        /// <param name="Index">当前进度</param>
        /// <param name="Total">总数</param>
        /// <param name="lpUserData"></param>
        [UnmanagedFunctionPointerAttribute(CallingConvention.StdCall)]
        public delegate void TASSDKOnProgressEvent(uint nErrorCode, uint Index, uint Total, IntPtr lpUserData);

     
        /// <summary>
        /// 初始化 AclasSDK.dll 动态连接库
        /// </summary>
        /// <param name="Adjuct">保留字 传null就可以了</param>
        /// <returns>成功返回 true</returns>
        [DllImport(LibraryName)]
     
        static public extern Boolean AclasSDK_Initialize(Pointer Adjuct = null);

        /// <summary>
        /// 释放 AclasSDK.dll动态库资源
        /// </summary>
        [DllImport(LibraryName)]
        static public extern void AclasSDK_Finalize();
        /// <summary>
        /// 获得设备信息
        /// </summary>
        /// <param name="Addr">设备整数Ip地址</param>
        /// <param name="Port">设备端口填入 0</param>
        /// <param name="ProtocolType">协议类型填入0表示32模式</param>
        /// <param name="DeviceInfo">输出的32模式设备信息结构体</param>
        /// <returns>成功返回 true</returns>
        [DllImport(LibraryName, CharSet = CharSet.Ansi)]
        static public extern Boolean AclasSDK_GetDevicesInfo(UInt32 Addr, UInt32 Port, UInt32 ProtocolType, ref TASSDKDeviceInfo DeviceInfo);
        [DllImport(LibraryName, CharSet = CharSet.Ansi)]
        static public extern int AclasSDK_GetNetworkSectionDevicesInfo(UInt32 Addr, UInt32 Port, UInt32 ProtocolType,
            IntPtr lpDeviceInfos, UInt32 dwCount);

        /// <summary>
        /// 异步执行，上传或下载数据，，调用后立即返回，具体进度通过回调函数报告
        /// </summary>
        /// <param name="Addr">设备整数Ip地址</param>
        /// <param name="Port">设备端口填入 0</param>
        /// <param name="ProtocolType">协议类型填入0表示32模式</param>
        /// <param name="ProcType">操作类型 下载到称填0上传填1修改填2（保留不可用）删除填3（清除所有plu） </param>
        /// <param name="DataType">数据类型十进制表示0是PLU类型3是热键类型</param>
        /// <param name="FileName">PLU文件地址</param>
        /// <param name="OnProgress">进度回调函数</param>
        /// <param name="lpUserData">用户自定义函数指针用于用户自己区分任务，本函数不处理直接原封返回，没有填null</param>
        /// <returns>返回任务句柄 当返回-1时表示设备无法连接执行失败</returns>
        [DllImport(LibraryName)]
        static public extern IntPtr AclasSDK_ExecTaskA(UInt32 Addr, UInt32 Port, UInt32 ProtocolType, UInt32 ProcType, UInt32 DataType,
            string FileName, TASSDKOnProgressEvent OnProgress, Pointer lpUserData);
        [DllImport(LibraryName, CallingConvention = CallingConvention.StdCall)]
        static public extern IntPtr AclasSDK_ExecTask(UInt32 Addr, UInt32 Port, UInt32 ProtocolType, UInt32 ProcType, UInt32 DataType,
                string FileName, TASSDKOnProgressEvent OnProgress, Pointer lpUserData);
            [DllImport(LibraryName)]
        static public extern IntPtr AclasSDK_ExecTaskW(UInt32 Addr, UInt32 Port, UInt32 ProtocolType, UInt32 ProcType, UInt32 DataType,
            string FileName, TASSDKOnProgressEvent OnProgress, Pointer lpUserData);
        [DllImport(LibraryName)]
        static public extern int AclasSDK_GetLastTaskError();
       
       /// <summary>
       /// 取消任务
       /// </summary>
       /// <param name="TaskHandle">要取消的任务句柄， 填0时取消所有任务</param>
        [DllImport(LibraryName)]
        static public extern void AclasSDK_StopTask(IntPtr TaskHandle);
        /// <summary>
        /// 同步执行任务 执行上传或下载数据，等待任务执行完再返回
        /// </summary>
        /// <param name="TaskHandle">任务句柄</param>
        [DllImport(LibraryName)]
        static public extern void AclasSDK_WaitForTask(IntPtr TaskHandle);
        /// <summary>
        /// 无回调函数方式执行任务
        /// </summary>
        /// <param name="Addr">设备整数Ip地址<</param>
        /// <param name="Port">设备端口填入 0</param>
        /// <param name="ProtocolType">协议类型填入0表示32模式</param>
        /// <param name="ProcType">操作类型 下载到称填0上传填1修改填2（保留不可用）删除填3（清除所有plu）</param>
        /// <param name="DataType">数据类型十进制表示0是PLU类型3是热键类型</param>
        /// <param name="FileName">PLU文件地址</param>
        /// <returns>返回0表示执行成功。258设备不存在259协议不支持266通讯异常等查表</returns>

        [DllImport(LibraryName)]
        static public extern int AclasSDK_Sync_ExecTask_PB (UInt32 Addr, UInt32 Port, UInt32 ProtocolType, UInt32 ProcType, UInt32 DataType, 
            string FileName);

        /// <summary>
        /// 无回调函数方式执行任务pb ansic版
        /// </summary>
        /// <param name="Addr"></param>
        /// <param name="Port"></param>
        /// <param name="ProtocolType"></param>
        /// <param name="ProcType"></param>
        /// <param name="DataType"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        [DllImport(LibraryName)]
        static public extern int AclasSDK_Sync_ExecTaskA_PB(UInt32 Addr, UInt32 Port, UInt32 ProtocolType, UInt32 ProcType, UInt32 DataType,
      string FileName);

        #endregion

        //***************************顶尖32模式内部数据结构声明***********************************************
        //bindList<Uipluitem> RPLUList = new List<Uipluitem>();
        private BindingList<Uipluitem> InuipluList = new BindingList<Uipluitem>();
  
        const string WritePLUFileName = "Plu.txt";
        const string WritePLUHotKeyFileName = "HotKey.key";
        int Nowindex, Nowtotal;
        string SuccessMessage = "未开始";
        //****************************功能实现正文***********************************************


        #region 普通常用方法
        /// <summary>
        /// 将字符串IP地址转换为无符号整数形式IP地址
        /// </summary>
        /// <param name="IPAdress">字符串IP地址</param>
        /// <returns>无符号整数形式IP地址</returns>
        public uint MakeHostToDWord(string IPAdress)
        {
            int i;
            string[] Segment;
            uint result;
            result = 0;

            Segment = IPAdress.Split('.');
            if (Segment.Length != 4)
                return result;
            for (i = 0; i < (Segment.Length); i++)
            {
                if ((Convert.ToUInt32(Segment[i]) >= 0) && (Convert.ToUInt32(Segment[i]) <= 255))
                {
                    result = result + Convert.ToUInt32(Convert.ToUInt32(Segment[i]) << ((3 - i) * 8));
                }
                else
                    return result;
            }
            return result;
        }
        /// <summary>
        ///在字典里通过value找key
        /// </summary>
        /// <param name="D_WeightUnitflag">字典</param>
        /// <param name="value">value</param>
        /// <returns>key值 或 null</returns>
        string GetDictionaryKey(Dictionary<string, string> D_WeightUnitflag, string value)
        {

            foreach (var key in D_WeightUnitflag.Keys)
            {
                if (D_WeightUnitflag[key].Equals(value))
                {
                    return key;
                }
            }
            return null;


        }

        /// <summary>
        /// 异步执行传入在状态回调函数
        /// </summary>
        /// <param name="errorcode">sdk中在错误号</param>
        /// <param name="index">sdk中的进度值</param>
        /// <param name="total">sdk中的总数</param>
        /// <param name="lpuserdata">null</param>
        void MytranprogessEvent(uint errorcode,uint index,uint total, IntPtr lpuserdata)
        {
            const string sInfoProgress = "进度: 当前: {0}/总数: {1}";
            const string sInfoComplete = "成功完成! 总数: {0}";
            const string sInfoStop = "操作停止!";
            const string sInfoFailed = "操作失败!";
            switch (errorcode)
            {
                case ASSDK_Err_Success:
                    {
                        
                   
                        Nowindex =(int)index;
                        Nowtotal = (int)total;

                        SuccessMessage = sInfoComplete;


                        break;
                    }
                case ASSDK_Err_Progress:

                    {
                        Nowindex = (int)index;
                        Nowtotal = (int)total;

                        SuccessMessage = sInfoProgress;
                        break;
                    }
                case ASSDK_Err_Terminate:
                    {
                        SuccessMessage = sInfoStop;
                        break;
                    }

                default:
                    SuccessMessage = sInfoFailed;
                    break;
            }
        }

/// <summary>
/// 演示报告进度的回调函数写法参考用
/// </summary>
/// <param name="nErrorCode"></param>
/// <param name="Index"></param>
/// <param name="Total"></param>
/// <param name="lpUserData"></param>
        public  void  OnprogressEvent(UInt32 nErrorCode, UInt32 Index, UInt32 Total, IntPtr lpUserData)
        {
            //const string sInfoProgress = "Progress: {0}/{1}";
            const string sInfoComplete = "Complete, Total: {0}";
            const string sInfoStop = "操作停止!";
            const string sInfoFailed = "操作失败!";

            switch (nErrorCode)
            {
                case ASSDK_Err_Success:
                    {
                        MessageBox.Show(string.Format(sInfoComplete, Total));
                        break;
                    }
                case ASSDK_Err_Progress:
                    {
                        //MessageBox.Show(string.Format(sInfoProgress, Index, Total));                        
                        break;
                    }
                case ASSDK_Err_Terminate:
                    {
                        MessageBox.Show(sInfoStop);
                        break;
                    }
                default:
                    MessageBox.Show(sInfoFailed);
                    break;
            }
        }

        #endregion



        #region 1.初始化
        /// <summary>
        ///  无参构造用于读取plu源文件文件初始化本类
        /// </summary>
        public Aclas32()
        {

            InitThisClass();

        }

        /// <summary>
        /// 有参 构造函数用于传输plu界面传输plu用
        /// </summary>
        /// <param name="InUIpluList">界面显示的plu信息的集合</param>
        public Aclas32(BindingList<Uipluitem> InUIpluList)
        {
            InuipluList = InUIpluList;
            InitThisClass();

        }
        /// <summary>
        /// 初始化本类 的方法 对各种解析定义
        /// </summary>
        public void InitThisClass()
        {
          //  *********能解析的单位定义*********
           D_WeightUnitflag.Add("4", "公斤");
            D_WeightUnitflag.Add("10", "pcs(kg)");
            D_WeightUnitflag.Add("7", "500g");
            D_WeightUnitflag.Add("1", "克");
            D_WeightUnitflag.Add("2", "10g");
            D_WeightUnitflag.Add("3", "100g");
            D_WeightUnitflag.Add("9", "pcs(g)");
            D_WeightUnitflag.Add("8", "600g");
            //  *********能解析的条码类型定义*********

        }

        #endregion


        #region 2.阶段 资源文件并解析出界面可显示的元素 因资源文件中 重量单位，条码类型等用数字表示不直观
       public bool CheckIsNeedFile(string readfilepath)
        {
            return FileoperHelper.CheckIsTextFile(readfilepath);
        }

       /// <summary>
        /// 匹配已知道的本类中 数字代表的重量单位
        /// </summary>
        /// <param name="weightunitflag"> 数字代表的重量单位</param>
        /// <returns>重量单位</returns>
       public string findMyWeightUnitFlag(string weightunitflag)
        {
            foreach (var item in D_WeightUnitflag.Keys)
            {
                if (item == weightunitflag)
                    return D_WeightUnitflag[item];

            }

            return weightunitflag;

        }
      
      
        /// <summary>
        /// 查找字符串在字符串数组中的下标
        /// </summary>
        /// <param name="sArrary">字符串数组</param>
        /// <param name="s">字符串</param>
        /// <returns>大于0 找到 -1 未找到</returns>
        int findPluIndex(string[] sArrary,string s)

        {
          
            for (int  i = 0;  i < sArrary.Length;  i++)
            {
                if (sArrary[i].ToLower() == s.ToLower())
                {
                  return i;
                }
               
            }
          return -1;
        }

        /// <summary>
        /// 读取32模式支持的源文件并解析
        /// </summary>
        /// <param name="readfilepath">源文件路径</param>
        /// <returns>返回 BindingList < Uipluitem >集合 </returns>
        public dynamic ReadPLuResourseFile(string readfilepath)
        {  
            //生成界面控件需要的PLU list集合
            BindingList<Uipluitem> RPLUList = new BindingList<Uipluitem>();

            StreamReader streamreader = new StreamReader(readfilepath, Encoding.Default);
            try
            {
               

                string sreadline = streamreader.ReadLine();
                string[] pluflagArrary = sreadline.Split('\t');
                int plunameindex = findPluIndex(pluflagArrary, "name1");
                int plucodeindex = findPluIndex(pluflagArrary, "ID");
                int pluLFcodeindex = findPluIndex(pluflagArrary, "ItemCode");
                int WeightUnitindex = findPluIndex(pluflagArrary, "unitid");
                int UnitPriceindex = findPluIndex(pluflagArrary, "price");
                int BarcodeCLassindex = findPluIndex(pluflagArrary, "barcodetype1");
                int weightFlagindex = findPluIndex(pluflagArrary, "DepartmentID");
                ///当以上 6个参数都找到 在执行查找具体 plu 数值不然 不执行返回 错误
                if (plucodeindex >= 0 && plucodeindex >= 0 && pluLFcodeindex >= 0 && WeightUnitindex >= 0 && UnitPriceindex >= 0 && BarcodeCLassindex >= 0)
                { 
                    int count = 1;
                    while (streamreader.Peek() != -1)
                    {
                        string sline = streamreader.ReadLine();
                        string[] sarrary = sline.Split('\t');
                      
                       Uipluitem rp = new Uipluitem();
                        rp.serialnumber = count.ToString();
                        rp.pluname= sarrary[plunameindex];
                        rp.PLUcode = sarrary[plucodeindex];
                        rp.lfcode= sarrary[pluLFcodeindex];
                        rp.price = sarrary[UnitPriceindex];
                        rp.unit = sarrary[WeightUnitindex];
                         rp.unitcode = rp.unit;
                        rp.WeightFlage = sarrary[weightFlagindex];
                        //？？？？？？后期 改？？？？？？？？？ 当条码格式为0表示为定义 将他强制转换为2目前
                        //有些称plu文件中并没有条码类型设置，就将其统一调整为 2 13位金额
                        rp.barcodeclass= sarrary[BarcodeCLassindex];

                        if (  rp.barcodeclass == "0"||rp.barcodeclass == "未设置")
                        {
                            rp.barcodeclassCode = "2";
                            rp.barcodeclass = rp.barcodeclassCode;
                        }
                        else
                            rp.barcodeclassCode = rp.barcodeclass;

                        rp.HotKey= rp.PLUcode;
                      
                        //***********************解析 出 单位****************************
                      
                        rp.unit = findMyWeightUnitFlag(rp.unit);
                        
                             
                 
                        //*********************将热键字符去掉前导0 并保留3位热键*****************************
                        Regex reg = new Regex(@"^0+");
                        string hotkey1 = rp.HotKey;
                        if (hotkey1.Length >= 3)
                        {
                            hotkey1 = rp.HotKey.Substring(rp.HotKey.Length - 3, 3);
                            rp.HotKey = reg.Replace(hotkey1, "");
                        }
                        else
                        {
                            rp.HotKey = reg.Replace(hotkey1, "");
                        }
                       RPLUList.Add(rp);
                       count++; 

                    }

                    streamreader.Close();
                }
            }


            catch (Exception)
            {
                streamreader.Close();
                throw;
            }




     
          
        return RPLUList;


        }


        #endregion


        #region 3.传输前准备阶段 将界面控件显示的plu内容转换为厂家动态库可传输的plu集合


        public void WriteUiPluListToFile(BindingList<Uipluitem> InuipluList)
        {
            //将PLU信息写入 PLU.txt文件中
            string WriteplufilePath = WritePLUFileName;

            StreamWriter sw = new StreamWriter(WriteplufilePath, false,Encoding.Default);
            try
            {
           string Aclas32Fileheard = "ID\tItemCode\tDepartmentID\tGroupID\tName1\tPrice\tUnitID\tBarcodeType1\tLabel1ID";
            sw.WriteLine(Aclas32Fileheard);
            foreach (var InPluitem in InuipluList)
            {
                 //？？？？？？后期 改？？？？？？？？？ 当条码格式为0表示为定义 将他强制转换为2目前
                    if (InPluitem.barcodeclassCode == "0")
                    {
                        InPluitem.barcodeclassCode = "2";

                    }

                    //将汉字的单位名 重新解析为 对应的数字
                    string getweightunit = GetDictionaryKey(D_WeightUnitflag, InPluitem.unit);

                    if (getweightunit != null)

                      InPluitem.unitcode=getweightunit;

                    else
                        //没找到单位对照表的按4 的方式公斤传
                        InPluitem.unitcode = "4";

                    string w = InPluitem.PLUcode + "\t" + InPluitem.lfcode + "\t" + InPluitem.WeightFlage + "\t" + "1" + "\t" + InPluitem.pluname
                            + "\t" + InPluitem.price + "\t" + InPluitem.unitcode + "\t" + InPluitem.barcodeclassCode+"\t"+ "1";
                sw.WriteLine(w);
            }
            
            sw.Close();
            }
            catch (Exception ex)
            {
                sw.Close();
                throw ex;
            }
            
 

            //将热键写入HotKey.key文件中
            string WriteHotkeyPath = WritePLUHotKeyFileName;
             var swhotkey = new StreamWriter(WriteHotkeyPath, false,Encoding.Default);
            try
            {
          
            string Aclas32HotKeyFileHeard = "ButtonIndex\tButtonValue";
            swhotkey.WriteLine(Aclas32HotKeyFileHeard);
            foreach (var uiplu in InuipluList)
            {
                int hotkey=1;
                try
                {
                    hotkey = Convert.ToInt32(uiplu.HotKey);
                }
                catch (Exception ex) 
                {
                    hotkey = 0;

                    throw ex;
                }
                if (hotkey > 0 && hotkey < 225)
                { 
                  string  w = uiplu.HotKey + "\t" + uiplu.PLUcode;
                    swhotkey.WriteLine(w);
                }
             }
            swhotkey.Close();
           
            }
            catch (Exception ex)
            {
                swhotkey.Close();
                throw ex;
            }
   


        }



        #endregion

        public bool Link_EWeightOK(string IPAdress, string port)
        {
            try
            {
                AclasSDK_Finalize();

                AclasSDK_Initialize();
                return true;

            }
            catch (Exception)
            {

                return false;
            }
            
        }

        public int StartTranfPLU(string IPAdress, string port)
        {
            //先写入plu.txt文件
            try
            {
              WriteUiPluListToFile(InuipluList);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Aclas32 模块中 写Plu.txt文件时发生错误！"+ex.Message, "写磁盘文件错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //MessageBox.Show(" Aclas32 模块 写Plus.txt文件时发生错误！");
                return -1;

            }
            TASSDKOnProgressEvent OnprogEvent = new TASSDKOnProgressEvent(MytranprogessEvent);
            //TASSDKOnProgressEvent OnprogEvent = new TASSDKOnProgressEvent(OnprogressEvent);

            uint IP= MakeHostToDWord(IPAdress);
            uint por = 0;
            uint ProcolType = 0;
            uint protype = 0;
            uint datatype = 0;
            IntPtr hdw = AclasSDK_ExecTaskA(IP, por, ProcolType, protype, datatype, WritePLUFileName, OnprogEvent, null);

            AclasSDK_WaitForTask(hdw);


            //成功返回执行在总数
            return Nowindex;
        }

        public int StartTranHotKey(string IPAdress, string port)
        {
            int Nowindex = 0;
            if (File.Exists(WritePLUHotKeyFileName))
            {
                
                TASSDKOnProgressEvent OnprogEvent = new TASSDKOnProgressEvent(MytranprogessEvent);
                //TASSDKOnProgressEvent OnprogEvent = new TASSDKOnProgressEvent(OnprogressEvent);

                uint IP = MakeHostToDWord(IPAdress);
                uint por = 0;
                uint ProcolType = 0;
                uint protype = 0;
              // datatype=3代表传送的是热键
                uint datatype = 3;
                IntPtr hdw = AclasSDK_ExecTaskA(IP, por, ProcolType, protype, datatype,WritePLUHotKeyFileName, OnprogEvent, null);

                AclasSDK_WaitForTask(hdw);


                //成功返回执行在总数
                return Nowindex;

            }
            else
            {
                return -1;
            }
                
        }

        public bool Close_EWeightConnect(string IPAdress, string port)
        {
            try
            {
                AclasSDK_Finalize();
                return true;    
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }
        }
    }

}
